from django.db import models
import os, logging
from django.utils.text import slugify

# logger = logging.getLogger(__name__)
# def movie_image_upload_to(instance, filename):
#     if instance.id is None:
#         # 如果 id 还没有生成，返回一个临时路径
#         return os.path.join('movies_images', filename)
#     ext = filename.split('.')[-1]
#     new_filename = f"{instance.id} - {slugify(instance.name)}.{ext}"
#    return os.path.join('movies_images', new_filename)

# Create your models here.
class Movie(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    price = models.IntegerField()
    description = models.TextField()
    image = models.ImageField(upload_to='movies_images/')

    def __str__(self):
        return str(self.id) + ' - ' + self.name

    # def save(self, *args, **kwargs):
    #     # 保存模型以生成 id
    #     super().save(*args, **kwargs)
    #
    #     # 如果 image 字段存在且文件名不符合预期，则重新保存 image
    #     if self.image:
    #         old_filename = os.path.basename(self.image.name)
    #         new_filename = os.path.basename(movie_image_upload_to(self, old_filename))
    #         if self.image.name != new_filename:
    #             # 重命名文件
    #             old_path = self.image.path
    #             new_path = os.path.join(os.path.dirname(old_path), new_filename)
    #             os.rename(old_path, new_path)
    #
    #             # 更新 image 字段的路径
    #             self.image.name = os.path.join('movies_images', new_filename)
    #             super().save(update_fields=['image'])
    #     else:
    #         super().save(*args, **kwargs)
    #
    #     logger.info(f"Movie saved with id: {self.id}, name: {self.name}, image: {self.image.name}")

class Review(models.Model):
    id = models.AutoField(primary_key=True)
    comment = models.TextField(max_length=255)
    date = models.DateTimeField(auto_now_add=True)
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' - ' + self.comment
